<template>
	<van-loading size="24px" vertical style="margin-top: 15%;">授权中...</van-loading>
</template>
<script>
import { setLocalStorage, getLocalStorage } from '@/utils/auth';
import {getToken,getMemberInfo,getPageList, getTheme} from '../../api/global.js'

export default {
	data() {
		return {};
	},
	methods: {
		authorization() {
			let code = '';
			let appid = '';
			let redirect_uri = window.location.href;
			redirect_uri=redirect_uri.split("/authorization")[0]
			code = this.getUrlCode().code; // 截取code
			appid = this.getUrlCode().appid; // appid
			let organiseId = this.getUrlCode().organiseId; // 截取code
			console.log(code, organiseId, appid);
			if (!code) {
				// 如果没有code，则去请求
				window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}?organiseId=${organiseId}&appid=${appid}&response_type=code&scope=snsapi_base&state=&connect_redirect=1#wechat_redirect`;
			} else {
			getToken({
						organiseId: organiseId
					})
					.then(res => {
						const t=this
						t.getIndexList();
						setLocalStorage('token', res.data.access_token);
						getMemberInfo({
								appid: appid,
								code: code
							})
							.then(res => {
								if (res.success) {
									setLocalStorage('openId', res.data.openId);
									this.$store.commit('setUser', res.data);
									setLocalStorage('userData', res.data);
									getTheme({
											organiseId: organiseId
										})
										.then(res => {
											if (res.success) {
											
											
											} else {
												this.$toast(res.message);
											}
										});
									this.$router.push({ path: getLocalStorage('now_url') });
								} else {
									window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}?organiseId=${organiseId}&appid=${appid}&response_type=code&scope=snsapi_base&state=&connect_redirect=1#wechat_redirect`;
								}
							});
					});
			}
		},
		getIndexList() {
			const t = this;
			let indexList = [];
			getPageList({
					pageIndex: 1,
					pageSize: 8,
					disabled: false
				})
				.then(res => {
					if (res.success) {
						for (let i in res.data) {
							let list = {
								text: res.data[i].name,
								iconName: res.data[i].iconUrl,
								oldIndex: res.data[i].apSort
							};
							indexList.push(list);
						}
						this.$store.commit('getList', indexList);
					} else {
						this.$toast(res.message);
					}
				});
		},
		getUrlCode() {
			// 截取url中的code方法
			var url = location.search;
			var theRequest = new Object();
			if (url.indexOf('?') != -1) {
				var str = url.substr(1);
				var strs = str.split('&');
				for (var i = 0; i < strs.length; i++) {
					theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
				}
			}
			return theRequest;
		}
	},
	mounted() {
		this.authorization();
	},
	created() {}
};
</script>
